package yxy.game.pm2.command.shop;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.ShopMessage;
import yxy.game.pm2.module.shop.handle.CreditUnionShopHandle;
import yxy.game.pm2.module.shop.handle.ShopHandle;
import yxy.game.pm2.module.union.UnionHandle;
import yxy.game.pm2.module.union.UnionHandle.UnionPlayerEntry;

/** 商店 积分联盟购买 */
@MessageType(proto = Command.CreditUnionShopBuy, classtype = ShopMessage.CreditUnionShopBuyRequest.class)
public class CMD_CreditUnionShopBuy extends Command<ShopMessage.CreditUnionShopBuyRequest> {

	@Override
	public void execute(MessageSource messageSource, ShopMessage.CreditUnionShopBuyRequest request) {
		String playerCode = messageSource.getTag();
		int id = request.getId();
		int num = request.getNum();

		ShopMessage.CreditUnionShopBuyResponse.Builder response = ShopMessage.CreditUnionShopBuyResponse.newBuilder();
		try {

			ShopHandle.checkBuyNumber(num);

			{
				// 检查是否已经有联盟
				UnionPlayerEntry entry = new UnionPlayerEntry(playerCode);
				Result result = new UnionHandle().checkPlayerUnion(entry);
				if (!result.equals(Result.UnionIn)) {
					send(messageSource, response, result);
					return;
				}
			}
			Result result = new CreditUnionShopHandle().buy(playerCode, id, num, response);
			send(messageSource, response, result);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, ShopMessage.CreditUnionShopBuyResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}